package udes.assassin;

import udes.assassin.R;
import udes.assassin.server.api.DataStructure.LobbyInfo.RoomState;
import udes.assassin.server.api.DataStructure.UserStructure;
import udes.assassin.server.api.Message.Message;
import udes.assassin.server.api.Message.LobbyMessage.LeavingMessage;
import udes.assassin.server.api.Message.LobbyMessage.LobbyUpdateMessage;
import udes.assassin.server.api.Message.LobbyMessage.ReadyMessage;
import udes.assassin.server.api.Message.LobbyMessage.StartMessage;
import udes.assassin.server.api.Message.LobbyMessage.UnReadyMessage;
import udes.assassin.structure.Game;
import udes.assassin.structure.Player;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class LobbyActivity extends Activity implements OnClickListener, MessageManager {

	private ArrayAdapter<Player> mAdapter;
    private Button mIntentionButton;
    private TextView mNumberOfPlayer;
    private AssassinApplication mAssassin;
	private ApplyMessageTask mTask;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Layout
        setContentView(R.layout.activity_lobby);
        
        // Get application
        mAssassin = (AssassinApplication) getApplication();
        mAssassin.mCurrentManager = this;
        
        // Get handle on UI
        mNumberOfPlayer = ((TextView) findViewById(R.id.label_number_of_player));
        mIntentionButton = ((Button) findViewById(R.id.button_player_intention));
        mIntentionButton.setOnClickListener(this);
    }
    
    @Override 
    public void onResume(){
    	super.onResume();
    	
    	// Update info on page
        updateGameInfo();
    	
    	if(mTask != null){
    		mTask.stop();
    	}
    	mTask = new ApplyMessageTask(this, mAssassin);
        mTask.execute(1);
	}
	
	@Override
	public void onPause()
	{
		super.onPause();
		mTask.stop();
	}

	public void onClick(View view) {
		Button clickedBtn = (Button) view;

        switch (clickedBtn.getId()) {
        	case R.id.button_player_intention: 
        		// create game
        		if(Global.getInstance().mIsGameOwner){
        			if(Global.getInstance().mGame.isAllPlayerReady()){
        				// start game
        				if(Global.getInstance().mGame.getNbOfPlayerInGame() > 1)
        				{
        					mAssassin.sendMessage(new StartMessage());
        				}
        				else
        				{
        					Toast.makeText(getApplicationContext(), R.string.error_forever_alone, Toast.LENGTH_SHORT).show();
        				}
        			}
        			else{
                		Toast.makeText(getApplicationContext(), R.string.error_player_not_ready, Toast.LENGTH_SHORT).show();
        			}
        		}
        		else{
        			if(Global.getInstance().mGame.getPlayer(Global.getInstance().mId).isReady()){
        				mAssassin.sendMessage(new UnReadyMessage());
        			}
        			else{
        				mAssassin.sendMessage(new ReadyMessage());
        			}
        			clickedBtn.setEnabled(false);
        		}
        		break;
        }
	}
	
	private void updateGameInfo(){
		// Update TextView
		mNumberOfPlayer.setText(Global.getInstance().mGame.getFormatedNbOfPlayerInGame());
		Log.d("LobbyActivity", "You are now " + Global.getInstance().mGame.getFormatedNbOfPlayerInGame() + " in the game.");
		
		// Update Button Info
		if(Global.getInstance().mIsGameOwner){
			mIntentionButton.setText(R.string.button_start_game);
			mIntentionButton.setEnabled(true);
		}
		else{
			if(Global.getInstance().mGame.getPlayer(Global.getInstance().mId).isReady()){
				mIntentionButton.setText(R.string.button_mark_as_waiting);
			}
			else{
				mIntentionButton.setText(R.string.button_mark_as_ready);
			}
			mIntentionButton.setEnabled(true);
		}
		
		// Instanciate adapter
		mAdapter = new PlayerListAdapter(this, Global.getInstance().mGame.getPlayers());
      	ListView lv = ((ListView) findViewById(R.id.player_list));
      	lv.setAdapter(mAdapter);
      	mAdapter.notifyDataSetChanged();
	}

	public boolean manage(Message aMessage) {
		 if(aMessage.getClass().equals(LobbyUpdateMessage.class)) {
			LobbyUpdateMessage casted = (LobbyUpdateMessage)aMessage;
			
			boolean isOwnerInLobby = false;
			
			for(UserStructure user : casted.info.users){
				if(user.realName.equals(casted.info.roomOwnerName)){
					isOwnerInLobby = true;
					break;
				}
			}
			
			if(isOwnerInLobby){
				System.out.println("Creating new game info");
				Global.getInstance().mGame = new Game(casted.info);
				
				if(casted.info.roomStatus == RoomState.STARTED){
					mTask.stop();
					finish();
			    	startActivity(new Intent(this, InGameActivity.class));
				}
				else{
					updateGameInfo();
				}
			}
			else{
				mAssassin.sendMessage(new LeavingMessage());
				final Toast tag = Toast.makeText(getApplicationContext(), R.string.error_host_leave_lobby, Toast.LENGTH_SHORT);
	      		tag.show();

	      		// This act as displaying a long toast
	      		new CountDownTimer(4000, 1000){
	      		    public void onTick(long millisUntilFinished) {tag.show();}
	      		    public void onFinish() {tag.show();}
	      		}.start();
	      		finish();
			}
			return true;
		}
		 
		return false;
	}


	public void onBackPressed (){
		mAssassin.sendMessage(new LeavingMessage());
		super.onBackPressed();
	}
}
